import {
	ref,
	computed,
	watch
} from "vue";

import {
	defineStore
} from "pinia";

import api from "@/api/api";
import router from "@/router";
import util from "@/utils/util";

import {
	ElMessage,
} from 'element-plus';


// 定义模块 用户
export const useUserStore = defineStore("user", () => {

	const originalUser = {
		nickName: "未登录",
		avatar: "",
		userId: "",
		// token: '',
	};

	// 整体参数
	const user = ref({
		...originalUser,
	});

	const avatar = computed(() => {
		const avatar = user.value.avatar;
		return avatar ? util.getHttpImageUrl(avatar) : util.getImageUrl('avatar.png')
	});
	const nickName = computed(() => user.value.nickName);
	const userId = computed(() => user.value.userId || "");
	const token = computed(() => {
		return localStorage.getItem("token") || '';
	});

	// 监听userId
	watch(userId, (n) => {
		console.log("watch userId", n);
	});

	// 登录
	function login(token) {
		// uni.setStorageSync("token", NewValue.token);
		// user.value = NewValue;
		if (token) localStorage.setItem("token", token);

		// 重新加载当前页面 permission.js 若登录则自动跳转首页
		// router.go(0);
		router.go(-1);

		// 进入首页
		// toIndex();
	}

	// 修改参数
	function update(NewValue) {
		user.value = NewValue;
	}

	// 退出登录 还原数据
	function logout() {
		user.value = originalUser;
		localStorage.setItem('token', '')

		// 重新加载当前页面 permission.js 若未登录则自动跳转login
		router.go(0);
		// uni.clearStorageSync("token");
	}

	return {
		user,
		avatar,
		nickName,
		userId,
		token,

		// function
		login,
		update,
		logout,
	};
});

// 系统配置
export const useConfigStore = defineStore("config", () => {

	const config = ref({})

	// 修改
	function update(NewValue) {
		config.value = NewValue;
	}

	return {
		config,
		update
	}

});